package cn.itcast.bos.web.action;


import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.util.MailUtils;
import cn.itcast.bos.util.SmsUtils;
import cn.itcast.bos.util.base.BaseAction;
import cn.itcast.crm.domain.Customer;
/**
 * @author xxx
 *
 */
@Controller
@Scope("prototype")
@ParentPackage("json-default")
@Namespace("/")
public class CustomerAction extends BaseAction<Customer> {
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	@Action(value="customer_sendSms")
	public String sendSms(){
		String randomCode = RandomStringUtils.randomNumeric(4);
		System.out.println(randomCode);
		//将短信验证码保存到session中
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
		//编写短信内容
		final  String msg = "尊敬的用户您好,本次获取的验证码为:"+ randomCode ;

		//使用ActiveMQ消息队列

		jmsTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone",model.getTelephone());
				mapMessage.setString("msg",msg);
				return mapMessage;
			}
		});
		/*String result = SmsUtils.sendSmsByHTTP(model.getTelephone(), msg);

		if (result.startsWith("000")){
			//发送成功
			System.out.println(result);
			return NONE;	
		} else {
			
			return null;
			//throw new RuntimeException("发送短信失败,信息码:" + result);
		}
	*/
		return  NONE;
	}


	private String checkcode;
	
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	
	
	
	@Autowired
	private RedisTemplate<String, String> redisTemple;
	
	
	
	
	@Action(value="customer_regist",results={
			@Result(name="success",type="redirect",location="signup-success.html"),
			@Result(name="input",type="redirect",location="signup.html")
	})
	
	public String customer_regist(){
		String checkcodeSession = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if(checkcode == null || !checkcodeSession.equals(checkcode)){
			System.out.println("用户名验证码错误");
			return INPUT;
		}
		System.out.println(model);
		WebClient.create("http://localhost:9002/crm_management/services/customerService/customer").
		accept(MediaType.APPLICATION_JSON).post(model);
		System.out.println("客户注册成功");
		//发送激活邮件
		//生成激活码
		String activecode = RandomStringUtils.randomNumeric(31);
		//将激活码保存到Redis,设置24小时失效
		redisTemple.opsForValue().set(model.getTelephone(), activecode,24,TimeUnit.HOURS);
		//调用MailUtils 发送激活邮件
		String content = "亲亲爱的用户你好,请务必于24小时内,激活账户否则你懂得,点击下面地址激活账户:<a href ='"+ MailUtils.activeUrl+"?telephone="
		+model.getTelephone()+"&actvecode="+activecode +"'>速运快递邮箱绑定地址</a>";
		MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());
		System.out.println(content);
		return SUCCESS;
	}
//激活邮箱
	private String actvecode;

	public void setActvecode(String actvecode) {
		this.actvecode = actvecode;
	}

	@Action(value="customer_activeMail")
	public String activeMail() throws IOException{
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		String activecodeRedis = redisTemple.opsForValue().get(model.getTelephone());
		if(activecodeRedis ==null ||!activecodeRedis.equals(actvecode)){
			//激活码无效
		//	http://localhost:9003/bos_fore/customer_activeMail?telephone=13888888881&actvecode=9255803530602820383775492831797
			ServletActionContext.getResponse().getWriter().println("激活码无效,请重新登录,绑定邮箱");
		}else {
			//激活码有效
			//防止重复绑定
			//调用crm webservice 查询客户信息,判断是否已经绑定
			Customer customer = WebClient.create("http://localhost:9002/crm_management/services/customerService/customer/telephone/"
					+model.getTelephone()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
			if(customer.getType() ==null || customer.getType() !=1) {
				//没有绑定,进行绑定
				WebClient.create("http://localhost:9002/crm_management/services/customerService/customer/updatetype/"+model.getTelephone()).get();
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功");
			}else {
				//已经绑定,
				ServletActionContext.getResponse().getWriter().println("邮箱已经绑定,无需重复绑定!");
				//删除Redis激活码
				redisTemple.delete(model.getTelephone());
			}
		}
		return NONE;
	}
	// 用户登录使用手机号与密码
	@Action(value = "customer_login",results = {
			@Result(name = "success",location = "index.html#/myhome",type = "redirect"),
			@Result(name = "login" ,location = "login.html",type = "redirect")
	})
	public  String customerLogin(){
		Customer customer = WebClient.create("http://localhost:9002/crm_management/services/customerService/customer/login?telephone=" +
				model.getTelephone() + "&password=" + model.getPassword()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
		if (customer ==null) {
			//登录失败
			return  "login";
		}else {
			//登录成功
			ServletActionContext.getRequest().getSession().setAttribute("customer",customer);
			return SUCCESS;
		}

	}
}



















